//
//  ActivityPageOne.m
//  eCourseApp
//
//  Created by 朱献国 on 2018/8/13.
//  Copyright © 2018年 Facebook. All rights reserved.
//

#import "ActivityPageOne.h"
#include <CommonCrypto/CommonCrypto.h>
#import "ECourseConstant.h"
#import "RCTEntryViewController.h"
#import "JZEClassPlayerController.h"

@interface ActivityPageOne ()

@property (weak, nonatomic) IBOutlet UITextField *userNameTF;

@property (weak, nonatomic) IBOutlet UITextField *passwordTF;

@property (weak, nonatomic) IBOutlet UITextField *pageName;
@property (weak, nonatomic) IBOutlet UITextField *classId;

@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activityIndicator;
@property (weak, nonatomic) IBOutlet UILabel *resultLab;

@property (weak, nonatomic) IBOutlet UIButton *homeBtn;
@property (weak, nonatomic) IBOutlet UIButton *jumpBtn;
@end

@implementation ActivityPageOne

- (void)viewDidLoad {
    [super viewDidLoad];
  self.navigationItem.title = @"模拟登录";
  self.activityIndicator.hidden = YES;
}

- (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];
  
  self.resultLab.text = @"";
  [self viewCanTouch:NO];
}

// 登录
- (IBAction)login:(UIButton *)sender {
  
  [self.view endEditing:YES];

  NSString *userName = self.userNameTF.text;
  NSString *password = self.passwordTF.text;


  NSMutableDictionary *params = [NSMutableDictionary dictionary];
  [params setObject:userName forKey:@"username"];

  NSString *shaPassWStr = [self sha256String:password];
  [params setObject:shaPassWStr forKey:@"password"];
  [params setObject:@"iOS,19,iPhone XXXX" forKey:@"deviceType"];

  [self networkForLogin:params];
  
//  JZEClassPlayerController *eClassPlayerController = [[JZEClassPlayerController alloc] init];
//  eClassPlayerController.videoUrl = @"http://test.video.juziwl.cn/elearning/20180820/bac84be788f846fb9535d5b2f2417f36.mp4";
//  [self.navigationController presentViewController:eClassPlayerController animated:YES completion:nil];
  
}

// 首页
- (IBAction)homePage:(UIButton *)sender {
  
  dispatch_async(dispatch_get_main_queue(), ^{
    [self.view endEditing:YES];

    RCTEntryViewController *entryViewController = [RCTEntryViewController new];
    ECourseConstant *eCourseConstant = [ECourseConstant sharedECourseConstant];
    eCourseConstant.eCourseFirstRouter = @"HomePage";
    entryViewController.param = [self getParam];
    [self.navigationController pushViewController:entryViewController animated:YES];
  });
  
}

// 跳转指定页
- (IBAction)jumpToPage:(UIButton *)sender {
  
  ECourseConstant *eCourseConstant = [ECourseConstant sharedECourseConstant];
  
  NSString *pageName = self.pageName.text;
  NSString *classId = self.classId.text;
  
  eCourseConstant.eCourseFirstRouter = pageName;
  
  if ([eCourseConstant.eCourseFirstRouter isEqualToString:@"DetailLesson"]) {
    [eCourseConstant.map setObject:classId forKey:@"entryCourseId"];
  }
  else {
    [eCourseConstant.map setObject:classId forKey:@"entryLessonId"];
  }
  eCourseConstant.userInfo.userName = @"王孟贵";
  
  dispatch_async(dispatch_get_main_queue(), ^{
    [self.view endEditing:YES];
    
    
    RCTEntryViewController *entryViewController = [RCTEntryViewController new];
    entryViewController.param = [self getParam];
    [self.navigationController pushViewController:entryViewController animated:YES];
  });
  
}

- (void)viewCanTouch:(BOOL)canTouch {
  self.homeBtn.userInteractionEnabled = canTouch;
  self.jumpBtn.userInteractionEnabled = canTouch;
}

// 加密
- (NSString *)sha256String:(NSString *)password {
  
  NSData *pwdData = [password dataUsingEncoding:NSUTF8StringEncoding];
  
  unsigned char result[CC_SHA256_DIGEST_LENGTH];
  CC_SHA256(pwdData.bytes, (CC_LONG)pwdData.length, result);
  NSMutableString *hash = [NSMutableString
                           stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
  for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) {
    [hash appendFormat:@"%02x", result[i]];
  }
  return hash;
}

- (NSDictionary *)getParam {
  ECourseConstant *eCourseConstant = [ECourseConstant sharedECourseConstant];
  
  NSMutableDictionary *res = [NSMutableDictionary dictionary];
  NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
  [userInfo setObject:eCourseConstant.userInfo.uuid forKey:@"uuid"];
  [userInfo setObject:eCourseConstant.userInfo.loginType forKey:@"loginType"];
  [userInfo setObject:eCourseConstant.userInfo.token forKey:@"token"];
  [userInfo setObject:eCourseConstant.userInfo.imId forKey:@"imId"];
  [res setObject:userInfo forKey:@"userInfo"];
  [res setObject:eCourseConstant.eCourseFirstRouter forKey:@"eCourseFirstRouter"];
  [res setObject:eCourseConstant.map forKey:@"map"];
  
  return @{@"ECourseConstant" : res};
}


- (void)networkForLogin:(NSDictionary *)param {
  
  // 1.创建url
  // 请求一个网页
  NSString *urlString = @"http://test.family.juziwl.cn/family/user/register/login";
  NSURL *url = [NSURL URLWithString:urlString];
  
  // 2.创建请求 并：设置缓存策略为每次都从网络加载 超时时间30秒
  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
  request.HTTPMethod = @"POST";
  request.HTTPBody = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:nil];
  [request setValue:@"text/html;charset=UTF-8" forHTTPHeaderField:@"Content-Type"]; // 默认是application/json;charset=UTF-8
  
  // 3.采用苹果提供的共享session
  NSURLSession *sharedSession = [NSURLSession sharedSession];
  
  // 4.由系统直接返回一个dataTask任务
  self.activityIndicator.hidden = NO;
  [self.activityIndicator startAnimating];
  NSURLSessionDataTask *dataTask = [sharedSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    // 网络请求完成之后就会执行，NSURLSession自动实现多线程
    NSLog(@"%@",[NSThread currentThread]);
    dispatch_async(dispatch_get_main_queue(), ^{
      [self.activityIndicator stopAnimating];
    });
    if (data && (error == nil)) {
      // 网络访问成功
      NSLog(@"网络访问成功 data=%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
      
      NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
      
      ECourseConstant *loginResponse =[ECourseConstant sharedECourseConstant];
      
      UserInfo *userInfo = [[UserInfo alloc] init];
      if ([[dict objectForKey:@"status"] integerValue] == 200) {
        NSDictionary *dic = [dict objectForKey:@"content"];
        userInfo.uuid = [dic objectForKey:@"userId"];
        userInfo.token = [dic objectForKey:@"token"];
        userInfo.loginType = [dic objectForKey:@"userType"];
        userInfo.imId = [dic objectForKey:@"imId"];
        loginResponse.userInfo = userInfo;
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
          self.resultLab.text = @"登录成功";
          [self viewCanTouch:YES];
        });
        
      }
      else {
        // 网络访问失败
        NSLog(@"网络访问失败 error=%@",error);
        dispatch_async(dispatch_get_main_queue(), ^{
          self.resultLab.text = @"登录失败";
        });
      }
      
    } else {
      // 网络访问失败
      NSLog(@"网络访问失败 error=%@",error);
      dispatch_async(dispatch_get_main_queue(), ^{
        self.resultLab.text = @"登录失败";
      });
    }
  }];
  
  // 5.每一个任务默认都是挂起的，需要调用 resume 方法
  [dataTask resume];
  
}



@end
